import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.key
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.snapshotFlow
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.navigation.NavHostController
import cn.edu.baiyunu.myapplication.ui.navigation.Screen
import cn.edu.baiyunu.myapplication.ui.screens.home.HomeScreen
import cn.edu.baiyunu.myapplication.ui.screens.profile.ProfileScreen
import cn.edu.baiyunu.myapplication.ui.screens.statistics.StatisticsScreen
import cn.edu.baiyunu.myapplication.ui.screens.transactions.TransactionsScreen
import kotlin.math.absoluteValue
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.launch

/**
 * 主页面水平滑动组件
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun MainPagerScreen(
    pagerState: PagerState,
    navItems: List<Screen>,
    navController: NavHostController
) {
    // 添加选项卡索引状态变量
    var selectedTabIndex by remember { mutableIntStateOf(pagerState.currentPage) }
    // 获取协程作用域
    val coroutineScope = rememberCoroutineScope()
    
    // 添加调试日志，监控页面状态
    LaunchedEffect(pagerState) {
        snapshotFlow { pagerState.currentPage }
            .distinctUntilChanged()
            .collect { page ->
                selectedTabIndex = page
                println("主页面监听 - 当前页面切换到: $page")
            }
    }
    
    // 使用HorizontalPager实现页面水平滑动
    HorizontalPager(
        state = pagerState,
        modifier = Modifier.fillMaxSize(),
        // 设置页面预加载，减少切换时的延迟
        beyondBoundsPageCount = 2, // 增加预加载数量，确保远距离跳转时有缓存
        // 使用key确保页面有唯一标识，基于索引而非路由，避免路由相关的缓存问题
        key = { it }
    ) { pageIndex ->
        // 安全获取当前页面对应的导航项
        val currentScreen = navItems.getOrNull(pageIndex)
        
        // 在key中使用pageIndex确保每个位置的内容是唯一的，而不受路由影响
        key(pageIndex) {
            // 为每个页面创建导航状态
            var navigateToTransactionDetail by remember { mutableStateOf<String?>(null) }
            var navigateToAddTransaction by remember { mutableStateOf(false) }
            var navigateToSettings by remember { mutableStateOf(false) }
            var navigateToBudget by remember { mutableStateOf(false) }
            var navigateToSavingsGoal by remember { mutableStateOf(false) }
            
            // 处理导航操作
            navigateToTransactionDetail?.let { transactionId ->
                LaunchedEffect(transactionId) {
                    navController.navigate("${Screen.TransactionDetail.route}/$transactionId")
                    navigateToTransactionDetail = null
                }
            }
            
            if (navigateToAddTransaction) {
                LaunchedEffect(Unit) {
                    navController.navigate(Screen.AddTransaction.route)
                    navigateToAddTransaction = false
                }
            }
            
            if (navigateToSettings) {
                LaunchedEffect(Unit) {
                    navController.navigate(Screen.Settings.route)
                    navigateToSettings = false
                }
            }
            
            if (navigateToBudget) {
                LaunchedEffect(Unit) {
                    navController.navigate(Screen.Budget.route)
                    navigateToBudget = false
                }
            }
            
            if (navigateToSavingsGoal) {
                LaunchedEffect(Unit) {
                    navController.navigate(Screen.SavingsGoal.route)
                    navigateToSavingsGoal = false
                }
            }
            
            // 使用modifier配置页面转换动画效果
            Box(
                modifier = Modifier
                    .fillMaxSize()
                    .graphicsLayer {
                        // 计算当前页面与视口中心的相对位置
                        val pageOffset = (
                            (pagerState.currentPage - pageIndex) + pagerState
                                .currentPageOffsetFraction
                        ).absoluteValue
                        
                        // 应用基于位置的变换
                        alpha = 1f - (pageOffset * 0.3f).coerceIn(0f, 0.3f)
                        
                        // 轻微缩放效果增强用户体验
                        val scale = 1f - (pageOffset * 0.05f).coerceIn(0f, 0.05f)
                        scaleX = scale
                        scaleY = scale
                    }
            ) {
                // 使用println帮助调试页面渲染
                println("渲染页面: index=$pageIndex, screen=${currentScreen?.route}")
                
                // 根据页面索引渲染对应内容
                when (currentScreen) {
                    Screen.Home -> {
                        HomeScreen(
                            navigateToBudget = { navigateToBudget = true },
                            navigateToTransaction = { transactionId ->
                                navigateToTransactionDetail = transactionId
                            },
                            navigateToAllTransactions = {
                                println("MainPagerScreen - 执行navigateToAllTransactions回调")
                                println("当前页面: ${pagerState.currentPage}, 目标页面: 1")
                                
                                // 方法1: 设置标签索引并使用pagerState滑动（之前的方法）
                                selectedTabIndex = 1
                                
                                // 方法2: 使用navController直接导航到交易页面
                                // 这是一种更可靠的导航方式，因为它使用了官方导航系统
                                navController.navigate(Screen.Transactions.route) {
                                    // 使用Transactions作为返回时的回退起点
                                    popUpTo(Screen.Home.route)
                                    launchSingleTop = true
                                }
                            }
                        )
                    }
                    Screen.Transactions -> {
                        TransactionsScreen(
                            navigateToTransaction = { transactionId ->
                                navigateToTransactionDetail = transactionId
                            },
                            navigateToAddTransaction = {
                                navigateToAddTransaction = true
                            }
                        )
                    }
                    Screen.Statistics -> {
                        StatisticsScreen()
                    }
                    Screen.Profile -> {
                        ProfileScreen(
                            navigateToSettings = { navigateToSettings = true },
                            navigateToSavingsGoal = { navigateToSavingsGoal = true }
                        )
                    }
                    else -> {
                        // 默认情况下显示空白页面
                        Box(modifier = Modifier.fillMaxSize())
                    }
                }
            }
        }
    }
} 